#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
开放商户 - 审核结果通知功能使用示例
"""

import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))

from jlpay.base.config import OrgConfig
from jlpay.services.org_service import JlpayOrgService
from jlpay.services.openmerch.notify.notify_audit_result_service import NotifyAuditResultService
from jlpay.exception.exceptions import HttpStatusCodeException


def main():
    # SM2公私钥
    sm2_public_key_pem = """-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEJJhFmjeMRp9GwShxtWunv6Wny//m
Dg2pcnu0llDQvIYo5O3R+al39NekciZ0BIrT21Y/QJrXgJIoyBr6STml6g==
-----END PUBLIC KEY-----"""

    sm2_private_key_pem = """-----BEGIN EC PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgHqOp471SMDsQml2G
2ErpZPLD2X7rbMqa6P1O9Zqlhe+gCgYIKoEcz1UBgi2hRANCAAQkmEWaN4xGn0bB
KHG1a6e/pafL/+YODalye7SWUNC8hijk7dH5qXf016RyJnQEitPbVj9AmteAkijI
GvpJOaXq
-----END EC PRIVATE KEY-----"""

    # 嘉联支付平台公钥
    jlpay_pub_key_pem = """-----BEGIN PUBLIC KEY-----
MIIBMzCB7AYHKoZIzj0CATCB4AIBATAsBgcqhkjOPQEBAiEA/////v//////////
//////////8AAAAA//////////8wRAQg/////v////////////////////8AAAAA
//////////wEICjp+p6dn140TVqeS89lCafzl4n1FauPkt28vUFNlA6TBEEEMsSu
LB8ZgRlfmQRGajnJlI/jC7/yZgvhcVpFiTNMdMe8Nzai9PZ3nFm9zuNraSFT0KmH
fMYqR0AC3zLlITnwoAIhAP////7///////////////9yA99rIcYFK1O79Ak51UEj
AgEBA0IABKZ3VWwH0Aw9xvOWXb+xM2gXyApWEAZLFy8UyIigp3ehOTwPJ693njrg
NavTLdzAtFBqXRreivlwBTIFy8iRgn8=
-----END PUBLIC KEY-----"""

    # 创建配置
    config = OrgConfig.builder() \
        .app_id("1vzougr30f9vcw") \
        .url("https://openapi-uat.jlpay.com") \
        .org_pri_key(sm2_private_key_pem) \
        .org_pub_key(sm2_public_key_pem) \
        .jlpay_pub_key(jlpay_pub_key_pem) \
        .build()
    
    # 创建服务
    org_service = JlpayOrgService.builder() \
        .config(config) \
        .build()

    # 创建审核结果通知服务
    notify_audit_result_service = NotifyAuditResultService(config)
    
    # 解析审核结果通知
    print("=== 解析审核结果通知 ===")
    try:
        # 模拟通知参数
        notify_param = {
            "method": "POST",
            "uri": "/notify",
            "alg": "SM3_WITH_SM2_WITH_DER",
            "sign": "MEYCIQCpHAZPdXEVbiGW17x9hY0JuEJ4eIX6Uo7Uxk9vczQk1wIhAPXsJHBVRQLiXTUFz15I8UHNLEcgWDwdDx5Uv8GN8Cuo",
            "nonce": "QpPPCyWZFlgL1dI4MHJHVY37hqMN5YGG",
            "timestamp": "1711536850",
            "body": '{"apply_id":"b8659ea518d14c99b78b5ad000a0729c","app_id":"1vzougr30f9vcw","audit_status":"01","merch_no":"849584358140108","sign_id":"SIGN123456","sign_status":"01","audit_failure":"","audit_detail":[]}'
        }
        
        apply_result_record = notify_audit_result_service.parse_notify(notify_param)

        if apply_result_record:
            print(f"解析成功")
            print(f"申请ID：{apply_result_record.apply_id}")
            print(f"机构号：{apply_result_record.app_id}")
            print(f"审核状态：{apply_result_record.audit_status}")
            print(f"商户号：{apply_result_record.merch_no}")
            print(f"协议编号：{apply_result_record.sign_id}")
            print(f"签约状态：{apply_result_record.sign_status}")
            print(f"审核驳回描述：{apply_result_record.audit_failure}")
            
            if apply_result_record.audit_detail:
                print("审核详情：")
                for detail in apply_result_record.audit_detail:
                    print(f"  字段名称：{detail.field_name}")
                    print(f"  字段值：{detail.field_value}")
                    print(f"  错误信息：{detail.error_msg}")
        else:
            print(f"解析失败")
    except HttpStatusCodeException as e:
        print(f"HTTP请求异常：{e}")
    except Exception as e:
        print(f"发生异常：{e}")


if __name__ == "__main__":
    main() 